import * as MediaLibrary from 'expo-media-library';
import * as ImagePicker from 'expo-image-picker';
import { Alert } from 'react-native';

export const SaveImg = async (imageUri: string): Promise<boolean> => {
  try {
    // 检查权限状态
    const { status } = await MediaLibrary.getPermissionsAsync();

    if (status !== 'granted') {
      // 请求权限
      const { status: newStatus } = await MediaLibrary.requestPermissionsAsync();

      if (newStatus !== 'granted') {
        Alert.alert('权限不足', '帮办管家需要相册权限来保存图片，请在设置中开启权限');
        return false;
      }
    }

    // 保存图片到相册
    const asset = await MediaLibrary.createAssetAsync(imageUri);

    // 尝试创建相册，如果已存在则添加到现有相册
    try {
      const album = await MediaLibrary.getAlbumAsync('帮办管家');
      if (album) {
        await MediaLibrary.addAssetsToAlbumAsync([asset], album, false);
      } else {
        await MediaLibrary.createAlbumAsync('帮办管家', asset, false);
      }
    } catch (albumError) {
      // 如果创建相册失败，图片仍然会保存到相册的默认位置
      console.log('创建相册失败，但图片已保存:', albumError);
    }

    return true;
  } catch (error) {
    console.error('保存图片失败:', error);
    throw error; // 让调用者处理错误
  }
};

export const SelectImg = async (): Promise<string | null> => {
  try {
    // 检查媒体库权限
    const { status } = await ImagePicker.getMediaLibraryPermissionsAsync();

    if (status !== 'granted') {
      // 请求权限
      const { status: newStatus } = await ImagePicker.requestMediaLibraryPermissionsAsync();

      if (newStatus !== 'granted') {
        Alert.alert('权限不足', '帮办管家需要相册权限来选择图片，请在设置中开启权限');
        return null;
      }
    }

    // 启动图片选择器
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images', 'videos'],
      allowsEditing: true,
      aspect: [1, 1], // 正方形裁剪
      quality: 0.8, // 图片质量
      videoMaxDuration: 60, // 视频最大时长（秒）
    });

    if (!result.canceled && result.assets && result.assets.length > 0) {
      return result.assets[0].uri;
    }

    return null;
  } catch (error) {
    console.error('选择图片失败:', error);
    Alert.alert('错误', '选择图片时发生错误，请重试');
    return null;
  }
};

export const TakePhoto = async (): Promise<string | null> => {
  try {
    // 检查相机权限
    const { status } = await ImagePicker.getCameraPermissionsAsync();

    if (status !== 'granted') {
      // 请求权限
      const { status: newStatus } = await ImagePicker.requestCameraPermissionsAsync();

      if (newStatus !== 'granted') {
        Alert.alert('权限不足', '帮办管家需要相机权限来拍照，请在设置中开启权限');
        return null;
      }
    }

    // 启动相机 - 添加中文本地化选项
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [1, 1], // 正方形裁剪
      quality: 0.8, // 图片质量
      // 这些选项可能有助于本地化，但主要还是依赖系统语言
      presentationStyle: ImagePicker.UIImagePickerPresentationStyle.FULL_SCREEN,
    });

    if (!result.canceled && result.assets && result.assets.length > 0) {
      return result.assets[0].uri;
    }

    return null;
  } catch (error) {
    console.error('拍照失败:', error);
    Alert.alert('错误', '拍照时发生错误，请重试');
    return null;
  }
}; 